package cn.jekun.shop.app.action;

import javax.annotation.Resource;

import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;

import cn.jekun.component.base.bean.ErrorMsg;
import cn.jekun.component.base.exceptions.BusinessException;
import cn.jekun.component.base.utils.EncryptUtil;
import cn.jekun.component.core.Constants;
import cn.jekun.component.core.bean.gen.TsAccount;
import cn.jekun.component.core.service.AccountPayService;
import cn.jekun.shop.common.service.AccountService;
import cn.jekun.shop.common.service.BanksService;

/**
 * 提现(个人app)
 * @author yuan
 *
 */
public class WithdrawAction extends AppBaseAction{
	private static final String AUTH_SHOP_MY_ACCOUNT_SETTLE="SHOP_MY_ACCOUNT_SETTLE";//提现
	
	@Resource(name=AccountService.BEAN_NAME)
	AccountService accountService;
	
	@Resource(name = BanksService.BEAN_NAME)
	BanksService banksService;
	
	@Resource(name = AccountPayService.BEAN_NAME)
	AccountPayService accountPayService;

	/**
	 * 提现
	 * @return
	 */
	public String withdraw(){
		JSONObject jsonObject=new JSONObject();
		try {
//			this.checkRight(AUTH_SHOP_MY_ACCOUNT_SETTLE);//检查权限
			//获取账户余额
			String userId=this.getUserId();
			this.validateLoginApp(); 
			this.validateSign(this.getLoginSign(),this.getUserId());
			
			JSONObject jsonAccountObject=accountPayService.querySettleAmount("", userId,Constants.TS_ACCOUNT_OWNER_TYPE.USER);
			String code=jsonAccountObject.getString("code");
			if(code.equals("0")){
				jsonObject.put(ErrorMsg.KEY_CODE, ErrorMsg.CALL_FAIL);
				jsonObject.put(ErrorMsg.KEY_MESSAGE,"没有找到个人支付账户。");
				return this.writeJson(jsonObject);
			}
			String settleAmount=jsonAccountObject.getString("settleAmount");//可提现
			Double settleAmountDouble=new Double(settleAmount);
			
			String balance=jsonAccountObject.getString("balance");//余额
			Double balanceDouble=new Double(balance);
			
			java.text.NumberFormat nf = java.text.NumberFormat.getInstance();
			nf.setGroupingUsed(false); 
			nf.setMinimumFractionDigits(2);
			
			//最低提现金额
			double min = cn.jekun.component.core.service.AccountService.getMin();
			int days = cn.jekun.component.core.service.AccountService.getDays();
			int maxTimes = cn.jekun.component.core.service.AccountService.getMaxTimes();
			
			jsonObject.put("min",nf.format(min)) ;//最低提现金额
			
			String tips = "提现免手续费,约1-3个工作日到账";
			if(min>0){
				tips += ",最低提现"+min+"元";
			}
			if(days >0 && maxTimes >0){
				tips += ",每"+days+"天最多提现"+maxTimes+"次";
			}
			tips+="。";
			
			jsonObject.put("tips",tips) ;//
			
			
			jsonObject.put("isSetPay",jsonAccountObject.getString("isSetPay")) ;//是否已经设置了支付密码
			jsonObject.put("balance",balanceDouble==null?"0.00":nf.format(balanceDouble)) ;//余额
			jsonObject.put("settleAmount",settleAmountDouble==null?"0.00":nf.format(settleAmountDouble));//可提现余额
			
			jsonObject.put(ErrorMsg.KEY_CODE, ErrorMsg.CALL_OK);
			jsonObject.put(ErrorMsg.KEY_MESSAGE,"调用成功");
		} catch (BusinessException e) {
			jsonObject = JSONObject.fromObject(e.getErrorMsg());
		} catch (Exception e) {
			jsonObject = JSONObject.fromObject(new ErrorMsg(e.getMessage()));
			e.printStackTrace();
		}
		return this.writeJson(jsonObject);
	}
	/**
	 * 提现申请
	 * @return
	 */
	public String settleApply(){
		JSONObject jsonObject=new JSONObject();
		
		String accountId = request.getParameter("accountId");//提现账户代码
		String bankNumber = request.getParameter("bankNumber");//银行账户
		String bankName = request.getParameter("bankName");//银行名称
		String accountName = request.getParameter("accountName");//账户姓名
		String amountStr = request.getParameter("amount");//提现金额
		String paypwd = request.getParameter("paypwd");//支付密码
		String _sign_key = request.getParameter("_sign_key");//加密
		
		this.validateLoginApp(); 
		this.validateSign(this.getLoginSign(),this.getUserId(),accountId,bankNumber,bankName,accountName,amountStr,paypwd,_sign_key);
		
		if (StringUtils.isBlank(accountId)) {
			jsonObject.put(ErrorMsg.KEY_CODE, ErrorMsg.CALL_FAIL);
			jsonObject.put(ErrorMsg.KEY_MESSAGE,"对不起，请选择提现的银行账户");
			return this.writeJson(jsonObject);
		}
		if (StringUtils.isBlank(paypwd)) {
			jsonObject.put(ErrorMsg.KEY_CODE, ErrorMsg.CALL_FAIL);
			jsonObject.put(ErrorMsg.KEY_MESSAGE,"对不起，请输入支付密码");
			return this.writeJson(jsonObject);
		}
		//检查提现金额
		if (StringUtils.isBlank(amountStr)) {
			jsonObject.put(ErrorMsg.KEY_CODE, ErrorMsg.CALL_FAIL);
			jsonObject.put(ErrorMsg.KEY_MESSAGE,"对不起，请输入提现的金额");
			return this.writeJson(jsonObject);
		}
		double amount = 0;
		try {
			amount = Double.parseDouble(amountStr);
		} catch (Exception e) {
			jsonObject.put(ErrorMsg.KEY_CODE, ErrorMsg.CALL_FAIL);
			jsonObject.put(ErrorMsg.KEY_MESSAGE,"对不起，提现金额必须是有效的数字");
			return this.writeJson(jsonObject);
			
		}
		if(amount <=0){
			jsonObject.put(ErrorMsg.KEY_CODE, ErrorMsg.CALL_FAIL);
			jsonObject.put(ErrorMsg.KEY_MESSAGE,"对不起，提现金额必须大于0");
			return this.writeJson(jsonObject);
		}
		if (StringUtils.isBlank(bankNumber)) {
			jsonObject.put(ErrorMsg.KEY_CODE, ErrorMsg.CALL_FAIL);
			jsonObject.put(ErrorMsg.KEY_MESSAGE,"对不起，非法银行账户");
			return this.writeJson(jsonObject);
		}
		if (StringUtils.isBlank(bankName)) {
			jsonObject.put(ErrorMsg.KEY_CODE, ErrorMsg.CALL_FAIL);
			jsonObject.put(ErrorMsg.KEY_MESSAGE,"对不起，非法银行名称");
			return this.writeJson(jsonObject);
		}
		if (StringUtils.isBlank(accountName)) {
			jsonObject.put(ErrorMsg.KEY_CODE, ErrorMsg.CALL_FAIL);
			jsonObject.put(ErrorMsg.KEY_MESSAGE,"对不起，非法账户姓名");
			return this.writeJson(jsonObject);
		}
		String md5 = EncryptUtil.md5(accountId+amountStr+bankNumber+bankName+accountName+paypwd);
		if (!md5.equals(_sign_key)) {
			jsonObject.put(ErrorMsg.KEY_CODE, ErrorMsg.CALL_FAIL);
			jsonObject.put(ErrorMsg.KEY_MESSAGE,"非法提交");
			return this.writeJson(jsonObject);
		}
		
		//获取账户信息
		String userId=this.getUserId();
		TsAccount tsAccount = this.accountService.one(userId);
		if(tsAccount == null){
			jsonObject.put(ErrorMsg.KEY_CODE, ErrorMsg.CALL_FAIL);
			jsonObject.put(ErrorMsg.KEY_MESSAGE,"对不起，没有找到个人支付账户。");
			return this.writeJson(jsonObject);
		}
		//提现申请
		String settleApplyId = null;//提现申请代码
		try{
			JSONObject jsonSettleApply=this.accountPayService.settleApply("", tsAccount.getAccountId(), amount+"", "",accountId, paypwd,Constants.SG_APPLY_TYPE.APP,this.getUserId());
			String code=jsonSettleApply.getString("code");
			String message=jsonSettleApply.getString("message");
			
			if(code.equals("0")){
				jsonObject.put(ErrorMsg.KEY_CODE, ErrorMsg.CALL_FAIL);
				jsonObject.put(ErrorMsg.KEY_MESSAGE,message);
				return this.writeJson(jsonObject);
			}
			settleApplyId=jsonSettleApply.getString("applyId");
			
			//settleApplyId = this.banksService.settleApply(this.getSessionUser().getUserId(),accountId, amount,fee,paypwd);
			this.logService.addShopAuditLog(AUTH_SHOP_MY_ACCOUNT_SETTLE, "申请提现成功，提现申请代码:"+settleApplyId);//记录操作日志
		}catch(Exception e){
			jsonObject.put(ErrorMsg.KEY_CODE, ErrorMsg.CALL_FAIL);
			jsonObject.put(ErrorMsg.KEY_MESSAGE,"增加提现申请发生错误:"+e.getMessage());
			return this.writeJson(jsonObject);
		}
		if(settleApplyId == null){
			jsonObject.put(ErrorMsg.KEY_CODE, ErrorMsg.CALL_FAIL);
			jsonObject.put(ErrorMsg.KEY_MESSAGE,"增加提现申请失败");
			return this.writeJson(jsonObject);
		}
		jsonObject.put(ErrorMsg.KEY_CODE, ErrorMsg.CALL_OK);
		jsonObject.put(ErrorMsg.KEY_MESSAGE,"申请成功,请等待银行处理");
		
		return this.writeJson(jsonObject);
		
	}
	
	/**
	 * 提现记录
	 * @return
	 */
	public String querySettle(){
		
		
		JSONObject jsonObject=new JSONObject();
		
		
		try {
			
			String beginMoney="";//request.getParameter("beginMoney");
			String endMoney="";//request.getParameter("endMoney");
			String beginDate="";//request.getParameter("beginDate");
			String endDate="";//request.getParameter("endDate");
			String bankName="";//request.getParameter("bankName");
			
			String pageSize = this.request.getParameter("pageSize");
			String currentPage = this.request.getParameter("currentPage");
			String userId =this.getUserId();
			
			this.validateLoginApp(); 
			this.validateSign(this.getLoginSign(),this.getUserId(),pageSize,currentPage);
//			formMap.put("shopId", shopId);
//			SqlUtis.convertBetweenValue(formMap, "commitTime");
//			SqlUtis.prepareSql(formMap
//					,SqlUtis.getSQL(formMap, "a."+SgSettleApply.COL_COMMIT_TIME,"commitTime", Types.DATE)
//					,SqlUtis.getSQL(formMap, "u."+RsUser.COL_REAL_NAME, realName, Types.VARCHAR,SqlUtis.LIKE)
//					,SqlUtis.getSQL(formMap, "u."+RsUser.COL_USER_NAME, userName, Types.VARCHAR,SqlUtis.LIKE)
//					);
			jsonObject = this.banksService.listSettleApply(userId,beginDate,endDate,beginMoney,endMoney,bankName,pageSize, currentPage);
			
			
			
			
			
		} catch (BusinessException e) {
			jsonObject = JSONObject.fromObject(e.getErrorMsg());
		} catch (Exception e) {
			jsonObject = JSONObject.fromObject(new ErrorMsg(e.getMessage()));
			e.printStackTrace();
		}
		
		return this.writeJson(jsonObject);
		
		
		
	}
}
